package io.renren.modules.app.service.index.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.modules.app.dao.company.YcCollectCompanyDao;
import io.renren.modules.app.dao.company.YcUserCollectJobDao;
import io.renren.modules.app.dao.info.YcComplaintRecordDao;
import io.renren.modules.app.entity.company.CompanyEntity;
import io.renren.modules.app.entity.company.YcCollectCompany;
import io.renren.modules.app.entity.company.YcUserCollectJob;
import io.renren.modules.app.entity.index.IndexRecruitEntity;
import io.renren.modules.app.entity.info.CollectData;
import io.renren.modules.app.entity.info.YcComplaintRecord;
import io.renren.modules.app.service.index.YcRecruitService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.entity.company.YcCompanyEntity;

import io.renren.modules.app.dao.index.YcRecruitDao;
import io.renren.modules.app.entity.index.YcRecruitEntity;


@Service("ycRecruitService")//标注此类为业务层类，并放入容器中
@RequiredArgsConstructor//构造方法注入
public class YcRecruitServiceImpl extends ServiceImpl<YcRecruitDao, YcRecruitEntity>
        implements YcRecruitService {

    private final YcRecruitDao ycRecruitDao;//通过构造方法注入dao
    private final YcCollectCompanyDao collectCompanyDao;
    private final YcUserCollectJobDao userCollectJobDao;
    private final YcComplaintRecordDao complaintRecordDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {//调用queryzwrapper的底层分页
        IPage<YcRecruitEntity> page = this.page(
                new Query<YcRecruitEntity>().getPage(params),
                new QueryWrapper<YcRecruitEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public JSONObject indexListData(Map<String, Object> params) {
        if (StringUtils.isNotEmpty(params.get("cityId").toString())) {
            String cityId = params.get("cityId").toString();
            cityId = cityId.substring(0, 4);
            params.put("cityId", cityId);
        }
        JSONObject result = new JSONObject();
        //初始返回对象
        List<IndexRecruitEntity> entities = new ArrayList<>();
        Integer bidCount = ycRecruitDao.getBidCount();
        params.put("bidCount", bidCount);
        //存入前三数据，list是有序集合，直接返回页面就是前三个，根据插入顺序排列
        List<IndexRecruitEntity> top3 = ycRecruitDao.getIndexDataList(params);
        //entities.addAll(top3);
        result.put("topList", top3);//1：集合中加入前三条
        //not-in过滤竞价数据，组装竞价对应的招聘id./notIn_recruit是拼接了竞价三条数据的id
        String notIn_recruit = "";
        for (IndexRecruitEntity entity : top3) {
            notIn_recruit += "'" + entity.getId() + "',";//把竞价前三条的id进行了拼接
        }
        if (notIn_recruit.endsWith(",")) {//判断最后一个字符串是否为逗号
            notIn_recruit = notIn_recruit.substring(0, notIn_recruit.length()-1);//括号内的是区间，（0-长度减1）减1意味着把最后一个逗号去除
        }
        //塞入非竞价查询参数map中
        params.put("notInId", notIn_recruit);//将自定义的"notInId"带去sql里过滤

        //过滤前三数据，stream()相当于一条流，把集合中的每一条流单独各自存放到strem流中，在过滤，
        //ycRecruitDao.getIndexAllDataList(params).stream().filter(recruit ->{
            // top3.stream()把前三个放到流里，anymatch用于判断， 让全部的id不为，竞价前三的id：recruit.getId()
        //    return top3.stream().anyMatch(top -> top.getId() != recruit.getId());
        //}).forEach(entities::add);//循环过滤结果集，

       // entities.addAll(ycRecruitDao.getIndexDataList2(params));//2：去除了前3条竞价的
        result.put("entities", ycRecruitDao.getIndexDataList2(params));
        return result;//return的entities是包含了前三竞价和非竞价（1+2）
    }

    /**
     * 查询全部职位信息
     */
    public List<IndexRecruitEntity> selectRecruitAllList (Map<String, Object> params) {
        return ycRecruitDao.getIndexDataList2(params);
    }


    /**
     * 通过招聘编号查询企业编号获取企业详情
     */
    public YcCompanyEntity getCompanyDetail (String id) {
        return ycRecruitDao.selectCompanyDetailById(id);
    }

    /**
     * 根据招聘id查询招聘信息
     */
    public YcRecruitEntity getRecruitById(String id) {
        return ycRecruitDao.selectById(id);
    }

    /**
     * 查询收藏数据
     */
    @Override
    public List<YcUserCollectJob> queryCollectJobList(String userId) {
        List<YcUserCollectJob> collectJobs = new ArrayList<>();
        if (StringUtils.isNoneEmpty(userId)) {
            collectJobs = userCollectJobDao
                .selectList(new LambdaQueryWrapper<YcUserCollectJob>()
                .eq(YcUserCollectJob::getUserId, userId));
        }
        return collectJobs;
    }

    /**
     * 查询收藏状态
     */
    @Override
    public boolean queryCollect(String type, String resumeId, String userId) {
        if (StringUtils.isNoneBlank(userId, resumeId, type)) {
            List<YcUserCollectJob> userCollectJobs = userCollectJobDao
                    .selectList(new LambdaQueryWrapper<YcUserCollectJob>()
                    .eq(YcUserCollectJob::getCollectId, resumeId)
                    .eq(YcUserCollectJob::getUserId, userId)
                    .eq(YcUserCollectJob::getCollectType, type));
            if (userCollectJobs.size() > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 个人添加收藏职位或公司数据
     */
    @Override
    public boolean addCollect(String type, String resumeId, String userId) {
        if (StringUtils.isNoneBlank(userId, resumeId, type)) {
            //查询是否已经收藏
            List<YcUserCollectJob> userCollectJobs = userCollectJobDao
                    .selectList(new LambdaQueryWrapper<YcUserCollectJob>()
                    .eq(YcUserCollectJob::getCollectId, resumeId)
                    .eq(YcUserCollectJob::getUserId, userId)
                    .eq(YcUserCollectJob::getCollectType, type));
            if (userCollectJobs.size() > 0) {
                return true;
            }
            YcUserCollectJob userCollectJob = new YcUserCollectJob();
            userCollectJob.setAddtime(new Date());
            userCollectJob.setDeletestatus(false);
            userCollectJob.setCollectId(Integer.parseInt(resumeId));
            userCollectJob.setCollectType(Integer.parseInt(type));
            userCollectJob.setDeletestatus(false);
            userCollectJob.setUserId(Integer.parseInt(userId));
            userCollectJobDao.insert(userCollectJob);
            return true;
        }
        return false;
    }

    /**
     * 取消收藏数据
     */
    @Override
    public boolean unCollect(String type, String resumeId, String userId) {
        if (StringUtils.isNoneBlank(type, resumeId, userId)) {
            LambdaQueryWrapper<YcUserCollectJob> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YcUserCollectJob::getUserId, userId);
            queryWrapper.eq(YcUserCollectJob::getCollectId, resumeId);
            queryWrapper.eq(YcUserCollectJob::getCollectType, type);
            userCollectJobDao.delete(queryWrapper);
            return true;
        }
        return false;
    }

    /**
     * 查询举报状态
     */
    @Override
    public boolean queryComplaint(String companyId, String userId) {
        if (StringUtils.isNoneEmpty(companyId, userId)) {
            LambdaQueryWrapper<YcComplaintRecord> queryWrapper =
                    new LambdaQueryWrapper<YcComplaintRecord>();
            queryWrapper.eq(YcComplaintRecord::getCompanyId, companyId);
            queryWrapper.eq(YcComplaintRecord::getUserId, userId);
            List<YcComplaintRecord> recordList = complaintRecordDao.selectList(queryWrapper);
            if (recordList.size() > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 添加举报数据
     */
    @Override
    public boolean doComplaint(String companyId, String userId, String content) {
        if (StringUtils.isNoneEmpty(companyId, userId, content)) {
            YcComplaintRecord complaintRecord = new YcComplaintRecord();
            complaintRecord.setAddtime(new Date());
            complaintRecord.setDeletestatus(false);
            complaintRecord.setContent(content);
            complaintRecord.setUserId(Integer.parseInt(userId));
            complaintRecord.setCompanyId(Integer.parseInt(companyId));
            complaintRecord.setComplaintStatus(0);
            return complaintRecordDao.insert(complaintRecord) > 0;
        }
        return false;
    }

    /**
     * 查询收藏数据
     */
    @Override
    public List<CollectData> queryCollectList(String userId) {
        List<CollectData> collectDataList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userId)) {
            return ycRecruitDao.selectCollectData(userId);
        }
        return collectDataList;
    }

    /**
     * 公司添加收藏简历数据
     */
    public boolean addCompanyCollect(String companyId, String resumeId, String userId) {
        if (StringUtils.isNoneBlank(companyId, resumeId)) {
            int id = new Random().nextInt(1000000000);
            YcCollectCompany company = new YcCollectCompany();
            company.setAddtime(new Date()).setDeletestatus(false)
                    .setCompanyId(Integer.parseInt(companyId))
                    .setResumeId(Integer.parseInt(resumeId)).setId(id);
            int row = collectCompanyDao.insert(company);
            if (row >0){
                YcUserCollectJob userCollectJob = new YcUserCollectJob();
                userCollectJob.setAddtime(new Date());
                userCollectJob.setCollectId(id)
                        .setCollectType(1).setDeletestatus(false)
                        .setUserId(Integer.parseInt(userId));
                userCollectJobDao.insert(userCollectJob);
                return true;
            }
        }
        return false;
    }



    /**
     * 通过公司编号查询招聘人信息
     * @param companyId
     * @return
     */
    public CompanyEntity getCompanyUser(Integer companyId) {
        if (Objects.nonNull(companyId)) {
            CompanyEntity entity = ycRecruitDao.selectCompanyUserByCompanyId(companyId);
            return entity;
        }
        return new CompanyEntity();
    }

    /**
     * 查询招聘福利待遇
     */
    @Override
    public List<String> getRecruitWelfare(String recruitId) {
        return ycRecruitDao.selectRecruitWelfare(recruitId);
    }

}